package com.smartdot.bluetoothidcarddemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huashi.bluetooth.HSBlueApi;
import com.huashi.bluetooth.HsInterface;
import com.huashi.bluetooth.IDCardInfo;
import com.smartdot.bluetoothidcarddemo.bean.IdcardBean;
import com.smartdot.bluetoothidcarddemo.bean.MiJieMessageBean;
import com.smartdot.bluetoothidcarddemo.bean.ReadCardEvent;
import com.smartdot.bluetoothidcarddemo.http.LifeCycleEvent;
import com.smartdot.bluetoothidcarddemo.http.ProgressBaseObserver;
import com.smartdot.bluetoothidcarddemo.http.RetrofitUtils;
import com.smartdot.bluetoothidcarddemo.utils.CommonUtils;
import com.smartdot.bluetoothidcarddemo.utils.ExcelUtil;
import com.smartdot.bluetoothidcarddemo.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

public class BlueToothActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "BlueToothActivity";
    private ListView lv;
    private MyAdapter adapter;
    private List<BluetoothDevice> bundDevices;
    private List<BluetoothDevice> notDevices;
    private String filepath;
    private Context context;
    private TextView tv_ts;
    private Button scanf;
    private boolean isConn = false;
    private HSBlueApi hsBlueApi;
    private boolean isAutoReadCard = true;
    private TextView tvConn;
    private TextView tv_people_number1;
    private TextView tv_people_number2;
    private TextView tv_people_number3;
    private TextView tv_result;
    private ImageView iv_icon;
    private TextView tv_name;
    private TextView tv_gender;
    private TextView tv_number;
    private TextView tv_address;
    private TextView tv_temperature_ok;
    private EditText et_temperature;
    private RecyclerView recyclerview;
    private TextView tv_daochu;
    private ArrayList<IdcardBean> listIdCard;
    //用于控制retrofit的生命周期，以便在destroy或其他状态时终止网络请求
    public PublishSubject<LifeCycleEvent> lifecycleSubject = PublishSubject.create();
    private BaseQuickAdapter mAdapter;
    private String idCard;

    //该方法用于提供lifecycleSubject（相当于实现了IBaseView中的getLifeSubject抽象方法）。
    //方便Presenter中直接通过IBaseView获取lifecycleSubject，而不用每次都作为参数传递过去
    public PublishSubject<LifeCycleEvent> getLifeSubject() {
        return lifecycleSubject;
    }

    @Override
    public void onPause() {
        lifecycleSubject.onNext(LifeCycleEvent.PAUSE);
        super.onPause();
    }

    @Override
    public void onStop() {
        lifecycleSubject.onNext(LifeCycleEvent.STOP);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isConn) {
            hsBlueApi.unInit();
            isConn = false;
        }
        lifecycleSubject.onNext(LifeCycleEvent.DESTROY);
        EventBus.getDefault().unregister(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

        context = this;
        initView();
        initListener();
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermission();
        } else {
            initBlueTooth();
        }
    }

    private void initView() {
        tvConn = findViewById(R.id.tv_conn);
        tv_people_number1 = findViewById(R.id.tv_people_number1);
        tv_people_number2 = findViewById(R.id.tv_people_number2);
        tv_people_number3 = findViewById(R.id.tv_people_number3);
        tv_result = findViewById(R.id.tv_result);
        iv_icon = findViewById(R.id.iv_icon);
        tv_daochu = findViewById(R.id.tv_daochu);
        tv_name = findViewById(R.id.tv_name);
        tv_gender = findViewById(R.id.tv_gender);
        tv_number = findViewById(R.id.tv_number);
        tv_address = findViewById(R.id.tv_address);
        tv_temperature_ok = findViewById(R.id.tv_temperature_ok);
        et_temperature = findViewById(R.id.et_temperature);
        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        recyclerview.setHasFixedSize(false);
        listIdCard = new ArrayList<>();
        listIdCard.add(new IdcardBean());
        mAdapter = getAdapter();
        mAdapter.setNewData(listIdCard);
        recyclerview.setAdapter(mAdapter);
    }

    private BaseQuickAdapter getAdapter() {

        return new BaseQuickAdapter<IdcardBean, BaseViewHolder>(R.layout.item_idcard_message) {
            @Override
            protected void convert(BaseViewHolder holder, IdcardBean bean) {
                int layoutPosition = holder.getLayoutPosition();
                TextView tv_item_number = holder.getView(R.id.tv_item_number);
                TextView tv_item_name = holder.getView(R.id.tv_item_name);
                TextView tv_item_idcard_number = holder.getView(R.id.tv_item_idcard_number);
                TextView tv_item_result = holder.getView(R.id.tv_item_result);
                TextView tv_item_temperature = holder.getView(R.id.tv_item_temperature);
                TextView tv_item_time = holder.getView(R.id.tv_item_time);
                if (layoutPosition == 0) {
                    tv_item_number.setText("序号");
                    tv_item_name.setText("姓名");
                    tv_item_idcard_number.setText("身份证号");
                    tv_item_result.setText("结果");
                    tv_item_temperature.setText("体温（℃）");
                    tv_item_time.setText("时间");
                } else {
                    tv_item_number.setText(bean.number + "");
                    tv_item_name.setText(bean.name);

                    tv_item_idcard_number.setText(CommonUtils.idEncrypt(bean.idNumber));
                    tv_item_result.setText(bean.result);
                    tv_item_temperature.setText(bean.temperature);
                    tv_item_time.setText(bean.time);
                }

            }
        };
    }

    private void initListener() {
        EventBus.getDefault().register(context);
        tvConn.setOnClickListener(this);
        tv_temperature_ok.setOnClickListener(this);
        tv_daochu.setOnClickListener(this);
    }

    private void initBlueTooth() {
        bundDevices = new ArrayList<>();
        notDevices = new ArrayList<>();
        adapter = new MyAdapter();
        filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wltlib";// 授权目录
        hsBlueApi = new HSBlueApi(this);
        hsBlueApi.init();
//        if (ret == -1) {
//            Toast.makeText(this, "初始化失败", Toast.LENGTH_LONG).show();
//        }
        hsBlueApi.setmInterface(new HsInterface() {
            @Override
            public void reslut2Devices(Map<String, List<BluetoothDevice>> map) {
                bundDevices = map.get("bind");
                notDevices = map.get("notBind");
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_conn) {
            // 连接
            showDialog();
        } else if (id == R.id.tv_temperature_ok) {
            // 提交
            Toast.makeText(BlueToothActivity.this, "ok", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.tv_daochu) {
            // 导出
            exportExcel(this);
        }
    }


    private void exportExcel(Context context) {
        String excel_filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AndroidExcelDemo";
        File file = new File(excel_filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String excelFileName = "/" + format.format(new Date()) + ".xls";
        String[] title = {"序号", "姓名", "身份证号", "结果", "体温", "时间"};
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String sheetName = format1.format(new Date());


        List<IdcardBean> demoBeanList = new ArrayList<>();
        for (int i = 0; i < listIdCard.size(); i++) {
            if (TextUtils.isEmpty(listIdCard.get(i).name)) {
                continue;
            }
            demoBeanList.add(listIdCard.get(i));
        }
        excel_filePath = excel_filePath + excelFileName;
        ExcelUtil.initExcel(excel_filePath, sheetName, title);

        ExcelUtil.writeObjListToExcel(demoBeanList, excel_filePath, context);
        Toast.makeText(this, "excel已导出至：" + excel_filePath, Toast.LENGTH_SHORT).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ReadCardEvent readCardEvent) {
        final IDCardInfo cardInfo = readCardEvent.getCardInfo();
//        Toast.makeText(getApplicationContext(), "读卡成功", Toast.LENGTH_SHORT).show();
        if(!TextUtils.isEmpty(idCard)&&TextUtils.equals(idCard,cardInfo.getIDCard())){
            Toast.makeText(getApplicationContext(), "请换下一张证", Toast.LENGTH_SHORT).show();
            return;
        }
        idCard = cardInfo.getIDCard();
        tv_name.setText(cardInfo.getPeopleName());
        tv_gender.setText(cardInfo.getSex());
        tv_number.setText(CommonUtils.idEncrypt(cardInfo.getIDCard()));
        tv_address.setText(cardInfo.getAddr());

        try {
            //最后一个数据传入1就是会再根目录的wltlib目录保存好读取到的正反面图片
//            Bitmap bitmaps = GetImg.ShowBmp(ic, BlueToothActivity.this, 1);
//            iv.setImageBitmap(bitmaps);
            // 身份证头像
            FileInputStream fis = new FileInputStream(filepath + "/zp.bmp");
            Bitmap bmp = BitmapFactory.decodeStream(fis);
            iv_icon.setImageBitmap(bmp);
            fis.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 拿到数据后请求网络
        String url = "https://ncov-api.cetccloud.com/oortcloud/ncov/ncov/queryByNo4EnterPrise";
        String serviceID = "3b9e0e956ce7432bbff75b3645621141";
        String secretKey = "2dbfd0144a0f46d7b9c604f9cb91f3e1";
        String phone = "15620606679";
        String password = "ll123456";
        String no = cardInfo.getIDCard();
        String name = cardInfo.getPeopleName();
        Observable<MiJieMessageBean> observable = RetrofitUtils.newInstence().getMessage(url, serviceID, secretKey, phone, password, no, name);
        RetrofitUtils.composeToSubscribe(observable, new ProgressBaseObserver<MiJieMessageBean>(context) {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onNext_(MiJieMessageBean miJieMessageBean) {
                String code = miJieMessageBean.code;
                if (TextUtils.equals(code, 200 + "")) {
                    tv_result.setText(miJieMessageBean.data.binglileixing);
                    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                    IdcardBean idcardBean = new IdcardBean(1, cardInfo.getPeopleName(), cardInfo.getIDCard(), miJieMessageBean.data.binglileixing, "", format.format(new Date()));
                    listIdCard.add(idcardBean);
                    mAdapter.setNewData(listIdCard);
                    switch (miJieMessageBean.data.binglileixing) {
                        case "正常人员":
                            tv_result.setBackgroundResource(R.color.green);
                            break;
                        case "疑似人员":
                            tv_result.setBackgroundResource(R.color.yellow);
                            break;
                        case "密接人员":
                            tv_result.setBackgroundResource(R.color.orange);
                            break;
                        case "确诊人员":
                            tv_result.setBackgroundResource(R.color.red);
                            break;
                    }
                }
            }

            @Override
            public void onError_(int errType, String errMessage, Throwable e) {
                LogUtils.eNormal("luoli", errMessage);
            }
        }, getLifeSubject());

    }

    private class AlwaysReadCardRunnable implements Runnable {
        @Override
        public void run() {
            while (isAutoReadCard) {
                synchronized (hsBlueApi) {
                    hsBlueApi.Authenticate(200);
                    ReadCardEvent cardEvent = new ReadCardEvent();
                    IDCardInfo ic = new IDCardInfo();
                    if (hsBlueApi.Read_Card(ic, 1500) == 1) {
                        int ret = hsBlueApi.Unpack(filepath, ic.getwltdata());// 照片解码
                        if (ret != 0) {// 读卡失败
                            return;
                        }
                        cardEvent.setCardInfo(ic);
                        EventBus.getDefault().post(cardEvent);
                        //读取成功阻塞1秒
                        SystemClock.sleep(1 * 1000);
                    }
                }
            }
        }
    }

    /**
     * 请求权限
     */
    private void requestPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(BlueToothActivity.this, new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN
                    , Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
                    , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        } else {
            initBlueTooth();
        }
    }

    private void showDialog() {
        if (isConn) {
            Toast.makeText(BlueToothActivity.this, "已连接设备", Toast.LENGTH_LONG).show();
            return;
        }
        if (bundDevices != null && notDevices != null) {
            bundDevices.clear();
            notDevices.clear();
        }
        final AlertDialog dialog;
        View diaView = View.inflate(BlueToothActivity.this, R.layout.dialog, null);
        tv_ts = (TextView) diaView.findViewById(R.id.tv_ts);
        lv = (ListView) diaView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        scanf = (Button) diaView.findViewById(R.id.scanf);
        AlertDialog.Builder builder = new AlertDialog.Builder(BlueToothActivity.this);
        builder.setView(diaView);
//        builder.setCancelable(false);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0 || position == bundDevices.size() + 1) {
                    return;
                }
                Log.i(TAG, "onItemClick: 正在连接");
                dialog.dismiss();
                BluetoothDevice d = null;
                if (position < bundDevices.size() + 1) {
                    d = bundDevices.get(position - 1);
                } else {
                    d = notDevices.get(position - 2 - bundDevices.size());
                }
                int ret = hsBlueApi.connect(d.getAddress());
                if (ret == 0) {
                    Toast.makeText(BlueToothActivity.this, "已连接", Toast.LENGTH_LONG).show();
                    tvConn.setText("设备已连接");
                    tvConn.setTextColor(R.color.white);
                    tvConn.setBackgroundResource(R.color.bg_color1);
                    String sam = hsBlueApi.Get_SAM(500);
//                    tv_Sam.setText("SAM：" + sam);
                    isConn = true;
                    // 连接成功后直接开启子线程一直读卡
                    Executors.newSingleThreadExecutor().execute(new AlwaysReadCardRunnable());
                } else {
                    Toast.makeText(BlueToothActivity.this, "连接失败", Toast.LENGTH_LONG).show();
                }
            }
        });
        scanf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hsBlueApi.scanf();
                tv_ts.setVisibility(View.INVISIBLE);
                scanf.setVisibility(View.INVISIBLE);
                lv.setVisibility(View.VISIBLE);
            }
        });
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
//            if (notDevices == null){
//                return bundDevices.size()+1;
//            }
            return bundDevices.size() + notDevices.size() + 2;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (position == 0) {
                TextView tv = new TextView(BlueToothActivity.this);
                tv.setBackgroundResource(R.color.app_item);
                tv.setTextColor(Color.WHITE);
                tv.setText("绑定设备");
                return tv;
            }
            if (position == bundDevices.size() + 1) {
                TextView tv = new TextView(BlueToothActivity.this);
                tv.setBackgroundResource(R.color.app_item);
                tv.setTextColor(Color.WHITE);
                tv.setText("其他设备");
                return tv;
            }
            View v = null;
            ViewHodler hodler;
            BluetoothDevice device = null;
            if (position < bundDevices.size() + 1) {
                device = bundDevices.get(position - 1);
            } else {
                device = notDevices.get(position - 2 - bundDevices.size());
            }
            if (convertView != null && convertView instanceof LinearLayout) {
                v = convertView;
                hodler = (ViewHodler) convertView.getTag();
            } else {
                v = View.inflate(BlueToothActivity.this, R.layout.item_dialog, null);
                hodler = new ViewHodler();
                hodler.tv_name = (TextView) v.findViewById(R.id.name);
                hodler.tv_address = (TextView) v.findViewById(R.id.mac);
                convertView = v;
                convertView.setTag(hodler);
            }
            hodler.tv_name.setText(device.getName());
            hodler.tv_address.setText(device.getAddress());
            return v;
        }

        class ViewHodler {
            private TextView tv_name, tv_address;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //如果requestCode为100 就走这里
            case 100:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initBlueTooth();
                } else {
                    //因为第一次的对话框是系统提供的 从这以后系统不会自动弹出对话框 我们需要自己弹出一个对话框
                    //进行询问的工作
                    startAlertDiaLog();
                }

                break;

        }

    }

    public void startAlertDiaLog() {

        android.app.AlertDialog.Builder alert = new android.app.AlertDialog.Builder(context);

        alert.setTitle("提示");
        alert.setMessage("需要申请权限");
        alert.setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //这里的立即开启 是打开手机的设置页面(打开相机权限)
                startSetting();

            }
        });
        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //如果用户还不打开 只能等用户下次点击时再次询问
//                Toast.makeText(BlueToothActivity.this,"当您点击我们会再次询问",Toast.LENGTH_SHORT).show();

            }
        });
        alert.create();
        alert.show();

    }

    public void startSetting() {

        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

        Uri uri = Uri.fromParts("package", getPackageName(), null);

        intent.setData(uri);

        startActivityForResult(intent, 10);

    }


}
